var api   = require('./utils/request');
var util  = require('./utils/util');
let cache = require('./utils/cache.js');
var siteInfo = require('config.js');
App({
  globalData: {
    isAndroid: false,//是否Android
    loginuser:{},    //登录用户
    appConfig:{},   //应用配置
    lbs:{},         //城市经纬度
    location:{},
    startBarHeight:20,
    navgationHeight:64
  },
  //生命周期函数--监听小程序初始化
  onLaunch:function (options) {
    this.apiroot = siteInfo.siteroot; //设置api地址
    this.appname = siteInfo.name;     //设置应用名称
    this.setNavigation();  //工具栏
    this.getParam(options);
    this.updateMiniapp();  //小程序更新
    this.isAndroid();      //判断操作系统是Android/iOS
    this.config()          //获取配置
  },
  //应用配置
  config: function () {
    if (util.isNull(cache.cacheGet('config'))) { 
      this.getConfig();
    }
    //获取配置
    if (util.isNull(cache.cacheGet('appConfig'))) {
      this.appConfig();
    }else{
      this.globalData.appConfig = cache.cacheGet('appConfig');
    }
    //登录用户信息
    if (!util.isNull(wx.getStorageSync('loginuser'))) {
      this.globalData.loginuser = wx.getStorageSync('loginuser');
    }
  },
  //应用配置
  getConfig: function () {
    api.Get('openapi/v1/config',(result) => {
      cache.cachePut('config',result.data,86400)
    })
  },
  //应用配置
  appConfig: function (callback) { 
    cache.cacheRem('appConfig');
    api.Get('api/v1/ais/config/index',(result)=>{
      this.globalData.appConfig = result.data;
      cache.cachePut('appConfig',result.data,432000)
      typeof callback == "function" && callback(result.data)
    })
  },
  //登录状态
  loginState:function (callback,islogin) {
    var session_id = wx.getStorageSync('session_id'),token = wx.getStorageSync('token'),loginuser= wx.getStorageSync('loginuser');
    if(util.isNull(session_id) || util.isNull(token) || util.isNull(loginuser)){
      if(islogin){
        wx.navigateTo({url: "/packageHelper/pages/login"})
      }else{
        typeof callback == "function" && callback(false)
      }
    }else{
      wx.checkSession({
        success(rel) {
          typeof callback == "function" && callback(true)
        },
        fail(rel) {
          if(islogin){
            wx.navigateTo({url: "/packageHelper/pages/login"})
          }else{
            typeof callback == "function" && callback(false)
          }
        }
      })
    }
  },
  //判断是否登录
  isLogin: function (callback) {
    if (util.isNull(wx.getStorageSync('session_id'))) {
      wx.checkSession({
        success(rel) {
          if (util.isNull(wx.getStorageSync('token')) || util.isNull(wx.getStorageSync('loginuser'))){
            wx.navigateTo({
              url: '/packageHelper/pages/login'
            })
          } else {
            typeof callback == "function" && callback(true)
          }
        },fail(rel) {
          wx.navigateTo({
            url: '/packageHelper/pages/login'
          })
        }
      })
    }else{
      typeof callback == "function" && callback(true)
    }
  },
  //微信小程序登录
  doLogin: function (options,callback) {
    let that = this;
    wx.login({
      success: function (res) {
        api.Post('openapi/v1/login', {
          code: res.code,
          user_info: options.detail.rawData,
          encrypted_data: options.detail.encryptedData,
          iv: options.detail.iv,
          signature: options.detail.signature,
          official_uid: wx.getStorageSync('official_uid'),
          invite_code: that.globalData.ucode
        }, function (result) {
          wx.setStorageSync('token', result.data.token);
          wx.setStorageSync('session_id',result.data.session_id);
          wx.setStorageSync('loginuser', result.data);
          that.globalData.loginuser = result.data;
          callback && callback(true);
        })
      },
      fail: function () {
        callback && callback(false);
      }
    });
  },
  //调用微信支付
  doWechatPay: function (data,successCallback,failCallback) {
    wx.requestPayment({
      timeStamp: data.timestamp,
      nonceStr: data.nonceStr,
      package: data.package,
      signType: data.signType,
      paySign: data.paySign,
      success: successCallback,
      fail: failCallback
    });
  },
  /**
    * 确认窗口并返回
    */
  wxLayer: function (message, callback) {
    wx.showModal({
      content: message,
      success: (rel) => {
        if (rel.confirm) {
          typeof callback == "function" && callback()
        }
      }
    })
  },
  /**
   * 弹窗提示
   */
  wxAlert: function (message, callback) {
    wx.showModal({
      content: message, showCancel: false,
      success: (rel) => {
        if (rel.confirm) {
          typeof callback == "function" && callback()
        }
      }
    })
  },
  //用全局变量保存邀请码
  getParam: function (options,callback) {
    let that = this;
    if (options.scene) {
      var options = util.strToArray(decodeURIComponent(options.scene));
      if (!util.isNull(options.ucode)) {
        that.globalData.ucode = options.ucode;
      }
    } else {
      if (!util.isNull(options.ucode)) {
        that.globalData.ucode = options.ucode;
      }
    }
    typeof callback == "function" && callback(options)
  },
  /**
   * 拨打电话
   */
  callPhone: function (e) {
    var phone_number = e.currentTarget.dataset.phone,
        config = wx.getStorageSync('config');
    wx.showModal({
      title: '拨打电话:' + phone_number,
      content: '联系我时请说明是在【' + config.app_name + '】看到的，谢谢！',
      success: function (res) {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: phone_number
          })
        }
      }
    })
  },
  /**
   * 判断操作系统是Android/iOS
   */
  isAndroid: function () {
    let that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.globalData.isAndroid = res.platform == "ios" ? false : true
      }
    })
  },
  setLocation:function (callback) {
    var that = this
    wx.chooseLocation({
      success: function (res) {
        that.globalData.lbs.lng = res.longitude;
        that.globalData.lbs.lat = res.latitude;
        wx.setStorageSync('lbs',that.globalData.lbs.lng+ '/' + that.globalData.lbs.lat)
        typeof callback == "function" && callback(true)
      },
      fail: function () {
        wx.getSetting({
          success: function (res) {
            var statu = res.authSetting;
            if (!statu['scope.userLocation']) {
              wx.showModal({
                title: '是否授权当前位置',
                content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
                success: function (tip) {
                  if (tip.confirm) {
                    wx.openSetting({
                      success: function (data) {
                        if (data.authSetting["scope.userLocation"] === true) {
                          wx.chooseLocation({
                            success: function (res) {
                              that.globalData.lbs.lng = res.longitude;
                              that.globalData.lbs.lat = res.latitude;
                              wx.setStorageSync('lbs',that.globalData.lbs.lng+ '/' + that.globalData.lbs.lat)
                              typeof callback == "function" && callback(true)
                            },
                          })
                        } else {
                          wx.showToast({title: '授权失败',icon: 'success',duration: 1000})
                          typeof callback == "function" && callback(false)
                        }
                      }
                    })
                  }
                }
              })
            }
          },
          fail: function () {
            wx.showToast({title: '调用授权窗口失败',duration: 1000})
            typeof callback == "function" && callback(false)
          }
        })
      }
    })
  },
  //自动获取经纬度
  getLocation: function (callback) {
    var that = this;
    wx.getSetting({
      success(rel) {
        if (rel.authSetting['scope.userLocation']) {
          wx.getLocation({type: 'wgs84',success:function(res){
            that.globalData.lbs.lng = res.longitude;
            that.globalData.lbs.lat = res.latitude;
            wx.setStorageSync('lbs',that.globalData.lbs.lng+ '/' + that.globalData.lbs.lat)
            typeof callback == "function" && callback(true)
          },fail(){
            typeof callback == "function" && callback(false)
          }}) 
        }else{
          wx.authorize({scope: 'scope.userLocation',success(rel) {
            wx.getLocation({type: 'wgs84',success: function (res) {
              that.globalData.lbs.lng = res.longitude;
              that.globalData.lbs.lat = res.latitude;
              wx.setStorageSync('lbs', that.globalData.lbs.lng+ '/' + that.globalData.lbs.lat)
              typeof callback == "function" && callback(true)
            },fail(){
              typeof callback == "function" && callback(false)
            }})
          },fail(rel){
            typeof callback == "function" && callback(false)
          }})
        }
      }
    }) 
  },
  //如果已经定位到城市就不再继续定位
  isLbs:function(callback){
    var data = Object.getOwnPropertyNames(this.globalData.location);
    if(data.length == 0){
      this.getLocation((rel)=>{
        this.getLbsApi(callback,rel);
      }) 
    }else{
      typeof callback == "function" && callback(true)
    }
  },
  //定位是手动设置坐标还是自动定位
  getLbs: function (callback,setLocation) {
    var setLocation = arguments[1] ? arguments[1] : false;
    if(setLocation){
      this.setLocation(rel =>{
        this.getLbsApi(callback,rel);
      })
    }else{
      this.getLocation((rel)=>{
        this.getLbsApi(callback,rel);
      }) 
    }
  },
  //读取API绑定坐标地址
  getLbsApi:function (callback,rel) {
    if(rel == true){
      this.api().Get('api/v1/ais/config/lib',(result) => {
        if(result.code == 200){
          this.globalData.location.adress = result.data.adress
          this.globalData.location.adcode = result.data.adcode
        }
        typeof callback == "function" && callback(result)
      })
    }else{
      typeof callback == "function" && callback({code:204})
    }
  },
  //重启发起定位
  restLocation: function (callback) {
    wx.showModal({
      content:'定位失败,请检查网络环境或手机定位权限',
      cancelText:'手动定位',confirmText	:'重新定位',
      success:(res) => {
        var setLocation = res.cancel?true:false
        this.getLbs((rel)=>{
          if(200 == rel.code){
            typeof callback == "function" && callback(rel)
          }else{
            typeof callback == "function" && callback({code:204})
          }
        },setLocation)
      }
    })
  },
  /**
   * 打开浏览器
   */
  webview:function (url) {
    wx.navigateTo({
      url: '/web/index?src=' + url
    })
  },
  //调用API
  api: function () {
    return api;
  },
  //工具集
  util: function () {
    return util;
  },
  //Navgation导航的高度
  setNavigation() {
    const  { height,top }  = wx.getMenuButtonBoundingClientRect();
    wx.getSystemInfo({
      success:(e) => {
        this.globalData.startBarHeight = top;
        this.globalData.navgationHeight = height+top+8;
      }
    })
  },
   /**
   * 更新小程序
   */
  updateMiniapp: function () {
    var that = this;
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      if(updateManager){
        //判断是否有新的小程序
        updateManager.onCheckForUpdate(function (res) {
          if (res.hasUpdate) {
            updateManager.onUpdateReady(function () {
              wx.clearStorage()    //清理缓存
              that.wxAlert('新版本已经升级完成，请重启应用!',() =>{
                updateManager.applyUpdate()
              })
            })
            //新的版本下载失败
            updateManager.onUpdateFailed(function () {
              wx.clearStorage()    //清理缓存
              that.wxAlert('新版本自动升级失败了~请您删除当前小程序，重新搜索打开哟~',() =>{
                updateManager.applyUpdate()
              })
            })
          }
        })
      }
    } else {
      this.wxAlert('当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。')
    }
  }
});